import loginPhoneAPi from '@/api/user/loginPhoneAPi'
import { getAppNav } from '@/App'
import CEmailOrPhoneCode from '@/components/user/CEmailOrPhoneCode'
import LocalStorageKey from '@/constant/LocalStorageKey'
import ILoginByPhoneForm from '@/model/form/user/ILoginByPhoneForm'
import { ToastError, ToastSuccess } from '@/util/CommonUtil'
import { maxTryNum, timeoutMsg } from '@/util/http/interceptor'
import Validator from '@/util/Validator'
import { Button, Form } from '@douyinfe/semi-ui'
import { ReactFieldError } from '@douyinfe/semi-ui/lib/es/form'
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'

export interface IPhoneLogin {
  loading: boolean
  setLoading: Dispatch<SetStateAction<boolean>>
}

export default function PhoneLogin(props: IPhoneLogin) {
  const [codeText, setCodeText] = useState('获取验证码')

  const timer = useRef<NodeJS.Timer>()

  useEffect(() => {
    return () => {
      clearTimer()
    }
  }, [timer])

  function clearTimer() {
    if (timer.current) {
      clearInterval(timer.current)
    }
  }

  return (
    <Form
      disabled={props.loading}
      className="w-300 m-t-10"
      onSubmit={(form) => {
        if (props.loading) return
        submitClick(form as ILoginByPhoneForm, props.setLoading)
      }}
      onSubmitFail={(errors: Record<string, ReactFieldError>) => {
        errors.code ? ToastError(errors.code as string) : null
      }}
    >
      <Form.Input
        field="phone"
        placeholder="手机号"
        noLabel
        rules={[{ required: true, message: '请输入手机号' }]}
        showClear
        validate={Validator['phoneValidate']}
      />
      <CEmailOrPhoneCode
        noLabel
        setCodeText={setCodeText}
        timer={timer}
        clearTimer={clearTimer}
        codeText={codeText}
        loading={props.loading}
        sendCodeType={2}
      ></CEmailOrPhoneCode>
      <div className="flex jc-sb">
        <Form.Checkbox field="rememberMe" noLabel>
          记住我
        </Form.Checkbox>
        <Form.Checkbox field="hiddenFlag" noLabel>
          隐身登录
        </Form.Checkbox>
      </div>
      <Button
        block
        size="large"
        loading={props.loading}
        htmlType="submit"
        className="m-t-10"
      >
        注册并登录
      </Button>
    </Form>
  )
}

// 点击提交按钮
function submitClick(
  form: ILoginByPhoneForm,
  setLoading: Dispatch<SetStateAction<boolean>>
) {
  setLoading(true) // 设置 loading状态

  if (form.hiddenFlag) {
    // socket 连接状态：1 在线 2 隐身
    localStorage.setItem(LocalStorageKey.SOCKET_TYPE, '2')
  } else {
    localStorage.setItem(LocalStorageKey.SOCKET_TYPE, '1')
  }

  doLoginPhoneApi(form, maxTryNum, setLoading)
}

// 调用手机号登录接口
function doLoginPhoneApi(
  form: ILoginByPhoneForm,
  maxTryNum: number,
  setLoading: Dispatch<SetStateAction<boolean>>
) {
  if (maxTryNum < 0) {
    ToastError(timeoutMsg, 5)
    setLoading(false) // 取消 loading状态
    return
  }
  loginPhoneAPi(form)
    .then((res) => {
      ToastSuccess('欢迎回来 (oﾟ▽ﾟ)o', 5)
      // 存储令牌
      localStorage.setItem(LocalStorageKey.JWT, res.data.data)
      // 跳转到首页
      getAppNav()('/')
    })
    .catch((e) => {
      if (e.message.includes('timeout')) {
        doLoginPhoneApi(form, maxTryNum - 1, setLoading)
      } else {
        ToastError(e.message, 5)
        setLoading(false) // 取消 loading状态
      }
    })
}
